package com.health.work.activity;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.health.work.R;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UploadUtil;
import com.health.work.utils.UserInfoUtils;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 发布商品
 * 
 * @author yinxing
 * 
 */
public class PublishActivity extends Activity {

	private Button back;
	private Button publish;
	private String name;
	private String price;
	private String pingZhi;
	private EditText namEditText;
	private EditText priceEditText;
	private EditText pingZhiEditText;
	private Bitmap photo;
	private ImageView camera;
	private String str_img = "";
	private String url = "";
	private final static int PUBSUCCESS = -1;
	private final static int PUBFAILE = -2;
	private final static int SUCCESS = 0;
	private final static int FAILE = 1;
	private final static int ERROR = 2;
	private final static int NODATA = 3;
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	private File mCurrentPhotoFile;// 照相机拍照得到的图片
	private EditText phoneEditText;
	private Thread thread;
	private String mobilePhoneNum;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				break;
			case FAILE:
				TipsUtil.showAlert(PublishActivity.this, null, "数据请求失败！");
				break;
			case ERROR:
				TipsUtil.showAlert(PublishActivity.this, null, "未知错误！");
				break;
			case NODATA:
				break;
			case PUBSUCCESS:
				pubSuccess();
				break;
			case PUBFAILE:
				pubFaile();
				break;
			default:
				break;
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.publish_layout);
		mobilePhoneNum = UserInfoUtils.getUserProperty(this,
				HEALTHPASSPORT.MOBILEPHONE);
		initPages();
	}

	private void initPages() {
		// TODO Auto-generated method stub
		back = (Button) findViewById(R.id.btnBack);
		publish = (Button) findViewById(R.id.btnUp);
		namEditText = (EditText) findViewById(R.id.name);
		priceEditText = (EditText) findViewById(R.id.price);
		pingZhiEditText = (EditText) findViewById(R.id.real);
		phoneEditText=(EditText)findViewById(R.id.phone);
		camera = (ImageView) findViewById(R.id.camera);
		camera.setOnClickListener(onClickListener);
		back.setOnClickListener(onClickListener);
		publish.setOnClickListener(onClickListener);

		
	}

	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			case R.id.btnUp:
				name = namEditText.getText().toString();
				price = priceEditText.getText().toString();
				pingZhi = pingZhiEditText.getText().toString();
				if (!"".equals(name) && !"".equals(price)
						&& !"".equals(pingZhi) && !"".equals(url)) {
					getData();
				} else {
					if ("".equals(name)) {
						Toast.makeText(PublishActivity.this, "请输入商品名称",
								Toast.LENGTH_SHORT).show();
					} else if ("".equals(pingZhi)) {
						Toast.makeText(PublishActivity.this, "请描述商品品质",
								Toast.LENGTH_SHORT).show();
					} else if ("".equals(price)) {
						Toast.makeText(PublishActivity.this, "请输入商品价钱",
								Toast.LENGTH_SHORT).show();
					} else if ("".equals(url)) {
						Toast.makeText(PublishActivity.this, "请上传商品图片",
								Toast.LENGTH_SHORT).show();
					} 
				}

				break;
			case R.id.camera:
				doPickPhotoAction();
				break;
			default:
				break;
			}
		}

	};

	/**
	 * 发布商品
	 */

	private void getData() {

		thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new RequestParamtersUtil().releaseProduct(mobilePhoneNum, name,
						pingZhi, url, price, new DefaultJSONData() {

							@Override
							public void parse(String result)
									throws JSONException {
								// TODO Auto-generated method stub
								if ("0".equals(result)) {
									handler.sendEmptyMessage(PUBSUCCESS);
								} else if ("1".equals(result)) {
									handler.sendEmptyMessage(PUBFAILE);
								}else{
									handler.sendEmptyMessage(PUBFAILE);
								}
								
							}

							@Override
							public void parse(JSONObject object)
									throws JSONException {
								// TODO Auto-generated method stub
							}

							@Override
							public void parse(JSONArray array)
									throws JSONException {
								// TODO Auto-generated method stub
							}
						});
			}
		});
		thread.start();
	}

	/**
	 * 发布成功
	 */
	private void pubSuccess() {
		Toast.makeText(PublishActivity.this, "恭喜你商品发布成功！", Toast.LENGTH_SHORT)
				.show();
		namEditText.setText("");
		priceEditText.setText("");
		pingZhiEditText.setText("");
		phoneEditText.setHint("");
	}

	/**
	 * 发布失败
	 */
	private void pubFaile() {

		Toast.makeText(PublishActivity.this, "商品发布失败，你可以继续尝试！",
				Toast.LENGTH_SHORT).show();
	}

	public void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this,
				android.R.style.Theme_Light);
		String cancel = "返回";
		String[] choices;
		choices = new String[2];
		choices[0] = "拍照"; // 拍照
		choices[1] = "从相册中选择"; // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle("选择方式");
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0: {
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							} else {
								Toast.makeText(PublishActivity.this, "出现异常",
										Toast.LENGTH_LONG).show();
							}
							break;

						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("CaseStorageActivity", "1:" + requestCode + "  2:" + resultCode);
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
			photo = data.getParcelableExtra("data");
			System.out.println(photo);
			camera.setImageBitmap(photo);
			// String imageStr = BitmapBase64.getBitmapStringBase64(photo);
			upFile(1, null, photo);
			break;
		}
		case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
			// doCropPhoto(mCurrentPhotoFile);
			photo = BitmapFactory.decodeFile(mCurrentPhotoFile.getPath());
			// photo=mCurrentPhotoFile;
			upFile(2, mCurrentPhotoFile, null);
			break;
		}
		}
	}

	protected void upFile(final int kind, final File file, final Bitmap bitmap) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {
			private ProgressDialog dialog2 = null;

			@Override
			protected void onPreExecute() {
				if (dialog2 != null) {
				} else {
					dialog2 = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog2.setCancelable(true);
				}
			}

			@Override
			protected Void doInBackground(Void... params) {
				if (kind == 2) {
					url = UploadUtil.uploadFile(file, HEALTHPASSPORT.URL_PIC,
							"file");
				} else {
					url = UploadUtil.uploadFile(bitmap, HEALTHPASSPORT.URL_PIC,
							"file");
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				dialog2.dismiss();
				dialog2 = null;
				if (url != null && url.length() > 0) {
					handler.sendEmptyMessage(SUCCESS);
					str_img = str_img + url + ";";
					Log.e("img str", str_img);
				} else {
				}
			}
		};
		asyncLoad.execute(null);
	}

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			mCurrentPhotoFile = new File(PHOTO_DIR, "health.jpg");// 给新照的照片文件命名
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	// 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} catch (Exception e) {
			Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 调用图片剪辑程序
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}
}
